<?php
require_once("../globals.php");
require_once("$srcdir/acl.inc");
require_once("$srcdir/sql.inc");
require_once("$srcdir/auth.inc");
require_once("$srcdir/formdata.inc.php");
require_once("$srcdir/classes/WSProvider.class.php");
require_once ("$srcdir/classes/postmaster.php");

$alertmsg = '';
$bg_msg = '';
$set_active_msg = 0;

/* Sending a mail to the admin when the breakglass user is activated only if $GLOBALS['Emergency_Login_email'] is set to 1 */
$bg_count = count($access_group);
$mail_id = explode(".", $SMTP_HOST);

for ($i = 0; $i < $bg_count; $i++) {
    if (($_REQUEST['access_group'][$i] == "Emergency Login") && ($_REQUEST['active'] == 'on') && ($_REQUEST['pre_active'] == 0)) {
        if (($_REQUEST['get_admin_id'] == 1) && ($_REQUEST['admin_id'] != "")) {
            $res = sqlStatement("select username from users where id={$_REQUEST["id"]}");
            $row = sqlFetchArray($res);
            $uname = $row['username'];
            $mail = new MyMailer();
            $mail->SetLanguage("en", $GLOBALS['fileroot'] . "/library/");
            $mail->From = "admin@" . $mail_id[1] . "." . $mail_id[2];
            $mail->FromName = "Administrator SAC";
            $text_body = "Hello Security Admin,\n\n The Emergency Login user " . $uname .
                    " was activated at " . date('l jS \of F Y h:i:s A') . " \n\nThanks,\nAdmin SAC.";
            $mail->Body = $text_body;
            $mail->Subject = "Emergency Login User Activated";
            $mail->AddAddress($_REQUEST['admin_id']);
            $mail->Send();
        }
    }
}
/* To refresh and save variables in mail frame */
if ($_REQUEST["privatemode"] == "user_admin") {
    if ($_REQUEST["mode"] == "update") {
        if ($_REQUEST["username"]) {
            // $tqvar = addslashes(trim($_REQUEST["username"]));
            $tqvar = trim(formData('username', 'G'));
            $user_data = mysql_fetch_array(sqlStatement("select * from users where id={$_REQUEST["id"]}"));
            sqlStatement("update users set username='$tqvar' where id={$_REQUEST["id"]}");
            sqlStatement("update groups set user='$tqvar' where user='" . $user_data["username"] . "'");
            //echo "query was: " ."update groups set user='$tqvar' where user='". $user_data["username"]  ."'" ;
        }
        if ($_REQUEST["taxid"]) {
            $tqvar = formData('taxid', 'G');
            sqlStatement("update users set federaltaxid='$tqvar' where id={$_REQUEST["id"]}");
        }
        if ($_REQUEST["state_license_number"]) {
            $tqvar = formData('state_license_number', 'G');
            sqlStatement("update users set state_license_number='$tqvar' where id={$_REQUEST["id"]}");
        }
        if ($_REQUEST["drugid"]) {
            $tqvar = formData('drugid', 'G');
            sqlStatement("update users set federaldrugid='$tqvar' where id={$_REQUEST["id"]}");
        }
        if ($_REQUEST["upin"]) {
            $tqvar = formData('upin', 'G');
            sqlStatement("update users set upin='$tqvar' where id={$_REQUEST["id"]}");
        }
        if ($_REQUEST["npi"]) {
            $tqvar = formData('npi', 'G');
            sqlStatement("update users set npi='$tqvar' where id={$_REQUEST["id"]}");
        }
        if ($_REQUEST["taxonomy"]) {
            $tqvar = formData('taxonomy', 'G');
            sqlStatement("update users set taxonomy = '$tqvar' where id= {$_REQUEST["id"]}");
        }
        if ($_REQUEST["lname"]) {
            $tqvar = formData('lname', 'G');
            sqlStatement("update users set lname='$tqvar' where id={$_REQUEST["id"]}");
        }
        if ($_REQUEST["job"]) {
            $tqvar = formData('job', 'G');
            sqlStatement("update users set specialty='$tqvar' where id={$_REQUEST["id"]}");
        }
        if ($_REQUEST["mname"]) {
            $tqvar = formData('mname', 'G');
            sqlStatement("update users set mname='$tqvar' where id={$_REQUEST["id"]}");
        }
        if ($_REQUEST["facility_id"]) {
            $tqvar = formData('facility_id', 'G');
            sqlStatement("update users set facility_id = '$tqvar' where id = {$_REQUEST["id"]}");
            //(CHEMED) Update facility name when changing the id
            sqlStatement("UPDATE users, facility SET users.facility = facility.name WHERE facility.id = '$tqvar' AND users.id = {$_REQUEST["id"]}");
            //END (CHEMED)
        }
        if ($GLOBALS['restrict_user_facility'] && $_REQUEST["schedule_facility"]) {
            sqlStatement("delete from users_facility
            where tablename='users'
            and table_id={$_REQUEST["id"]}
            and facility_id not in (" . implode(",", $_REQUEST['schedule_facility']) . ")");
            foreach ($_REQUEST["schedule_facility"] as $tqvar) {
                sqlStatement("replace into users_facility set
                facility_id = '$tqvar',
                tablename='users',
                table_id = {$_REQUEST["id"]}");
            }
        }
        
        if($_REQUEST["schedule_medic"]){
        $handler_id = $_SESSION['authUserID'];
        sqlStatement(
                "delete from user_handler "
                . "where handler_id = $handler_id"
        );
        foreach($_REQUEST["schedule_medic"] as $smvar){
            sqlStatement( 
                    "insert into user_handler (handler_id, user_id)"
                    . " values ($handler_id, $smvar)"
            );
        }
        
    }
        
        if ($_REQUEST["fname"]) {
            $tqvar = formData('fname', 'G');
            sqlStatement("update users set fname='$tqvar' where id={$_REQUEST["id"]}");
        }

        //(CHEMED) Calendar UI preference
        if ($_REQUEST["cal_ui"]) {
            $tqvar = formData('cal_ui', 'G');
            sqlStatement("update users set cal_ui = '$tqvar' where id = {$_REQUEST["id"]}");

            // added by bgm to set this session variable if the current user has edited
            //   their own settings
            if ($_SESSION['authId'] == $_REQUEST["id"]) {
                $_SESSION['cal_ui'] = $tqvar;
            }
        }
        //END (CHEMED) Calendar UI preference

        if (isset($_REQUEST['default_warehouse'])) {
            sqlStatement("UPDATE users SET default_warehouse = '" .
                    formData('default_warehouse', 'G') .
                    "' WHERE id = '" . formData('id', 'G') . "'");
        }

        if (isset($_REQUEST['irnpool'])) {
            sqlStatement("UPDATE users SET irnpool = '" .
                    formData('irnpool', 'G') .
                    "' WHERE id = '" . formData('id', 'G') . "'");
        }
        
        //VicarePlus: Empty string of SHA1 is validated
        if ($_REQUEST["newauthPass"] && $_REQUEST["newauthPass"] != "da39a3ee5e6b4b0d3255bfef95601890afd80709") { // account for empty
            $tqvar = formData('newauthPass', 'G');
// When the user password is updated and the password history option is enabled, update the password history in database. A new password expiration is also calculated
            if ($GLOBALS['password_history'] != 0) {
                $updatepwd = UpdatePasswordHistory($_REQUEST["id"], $tqvar);
            } else {
                sqlStatement("update users set password='$tqvar' where id={$_REQUEST["id"]}");
                if ($GLOBALS['password_expiration_days'] != 0) {
                    $exp_days = $GLOBALS['password_expiration_days'];
                    $exp_date = date('Y-m-d', strtotime("+$exp_days days"));
                    sqlStatement("update users set pwd_expiration_date='$exp_date' where id=$userid");
                }
            }
        }

        // for relay health single sign-on
        if ($_REQUEST["ssi_relayhealth"]) {
            $tqvar = formData('ssi_relayhealth', 'G');
            sqlStatement("update users set ssi_relayhealth = '$tqvar' where id = {$_REQUEST["id"]}");
        }

        $tqvar = $_REQUEST["authorized"] ? 1 : 0;
        $actvar = $_REQUEST["active"] ? 1 : 0;
        $calvar = $_REQUEST["calendar"] ? 1 : 0;
        $providers_auth_by_provider = $_REQUEST["providers_auth_by_provider"] ? 1 : 0;
        $details_auth_by_provider = $_REQUEST["details_auth_by_provider"] ? 1 : 0;
        
        sqlStatement("UPDATE users SET authorized = $tqvar, active = $actvar " .
                ", providers_auth_by_provider=$providers_auth_by_provider, details_auth_by_provider=$details_auth_by_provider, ".
                "calendar = $calvar, see_auth = '" . $_REQUEST['see_auth'] . "' WHERE " .
                "id = {$_REQUEST["id"]}");
        //Display message when Emergency Login user was activated 
        $bg_count = count($_REQUEST['access_group']);
        for ($i = 0; $i < $bg_count; $i++) {
            if (($_REQUEST['access_group'][$i] == "Emergency Login") && ($_REQUEST['pre_active'] == 0) && ($actvar == 1)) {
                $show_message = 1;
            }
        }
        if (($_REQUEST['access_group'])) {
            for ($i = 0; $i < $bg_count; $i++) {
                if (($_REQUEST['access_group'][$i] == "Emergency Login") && ($_REQUEST['user_type']) == "" && ($_REQUEST['check_acl'] == 1) && ($_REQUEST['active']) != "") {
                    $set_active_msg = 1;
                }
            }
        }
        if ($_REQUEST["comments"]) {
            $tqvar = formData('comments', 'G');
            sqlStatement("update users set info = '$tqvar' where id = {$_REQUEST["id"]}");
        }
        $erxrole = formData('erxrole', 'G');
        sqlStatement("update users set newcrop_user_role = '$erxrole' where id = {$_REQUEST["id"]}");

        if (isset($phpgacl_location) && acl_check('admin', 'acl')) {
            // Set the access control group of user
            $user_data = mysql_fetch_array(sqlStatement("select username from users where id={$_REQUEST["id"]}"));
            set_user_aro($_REQUEST['access_group'], $user_data["username"], formData('fname', 'G'), formData('mname', 'G'), formData('lname', 'G'));
        }

        $ws = new WSProvider($_REQUEST['id']);
    }
    ?>
    <html>
        <head>
            <?php html_header_show(); ?>
            <link rel="stylesheet" type="text/css" href="<?php echo $GLOBALS['webroot'] ?>/patients/css/nightingale.css" >

            <script language='JavaScript'>
                setTimeout(function() {
                    parent.$.fancybox.close();
                }, 1000);
            </script>
        </head>

        <body class="body_top">
        <center>
            <p class="text">
    <?php echo "Guardado con &eacute;xito"; ?>  
            </p>
            <p class="text">
                Este dialogo se cerrar&aacute; autom&aacute;ticamente...
            </p>
        </center>
    </body>
    </html>
    <?php
    exit;
}

  
/* To refresh and save variables in mail frame  - Arb */
if (isset($_REQUEST["mode"])) {
    if ($_REQUEST["mode"] == "new_user") {
        if ($_REQUEST["authorized"] != "1") {
            $_REQUEST["authorized"] = 0;
        }
        // $_REQUEST["info"] = addslashes($_REQUEST["info"]);
        $calvar = $_REQUEST["calendar"] ? 1 : 0;

        $res = sqlStatement("select distinct username from users where username != ''");
        $doit = true;
		
		//alert(trim($_REQUEST['rumple']));
		
        while ($row = mysql_fetch_array($res)) {
            if ($doit == true && $row['username'] == trim($_REQUEST['rumple2'])) {
                $doit = false;
            }
        }
		
		
        if ($doit == true) {
				
            //if password expiration option is enabled,  calculate the expiration date of the password
            if ($GLOBALS['password_expiration_days'] != 0) {
                $exp_days = $GLOBALS['password_expiration_days'];
                $exp_date = date('Y-m-d', strtotime("+$exp_days days"));
            }
            $prov_id = idSqlStatement("insert into users set " .
                    "username = '" . trim($_REQUEST['rumple2']) .
                    "', password = '" . trim($_REQUEST['newauthPass']) .
                    "', fname = '" . trim($_REQUEST['fname']) .
                    "', mname = '" . trim($_REQUEST['mname']) .
                    "', lname = '" . trim($_REQUEST['lname']) .
                    "', federaltaxid = '" . trim($_REQUEST['federaltaxid']) .
                    "', state_license_number = '" . trim($_REQUEST['state_license_number']) .
                    "', newcrop_user_role = '" . trim($_REQUEST['erxrole']) .
                    "', authorized = '" . trim($_REQUEST['authorized']) .
                    "', info = '" . trim($_REQUEST['info']) .
                    "', federaldrugid = '" . trim($_REQUEST['federaldrugid']) .
                    "', upin = '" . trim($_REQUEST['upin']) .
                    "', npi  = '" . trim($_REQUEST['npi']) .
                    "', taxonomy = '" . trim($_REQUEST['taxonomy']) .
                    "', facility_id = '" . trim($_REQUEST['facility_id']) .
                    "', specialty = '" . trim($_REQUEST['specialty']) .
                    "', see_auth = '" . trim($_REQUEST['see_auth']) .
                    "', cal_ui = '3'
                    , providers_auth_by_provider = '1'                        
                    , default_warehouse = '" . trim($_REQUEST['default_warehouse']) .
                    "', irnpool = '" . trim($_REQUEST['irnpool']) .
                    "', calendar = '" . $calvar .
                    "', pwd_expiration_date = '" . trim("$exp_date") .
                    "', speciality = '" . trim($_REQUEST['spaciality']).
                    "'");
                    
            
			
            //set the facility name from the selected facility_id
             sqlStatement("UPDATE users, facility SET users.facility = facility.name WHERE facility.id = '" . trim($_REQUEST['facility_id']) . "' AND users.username = '" . trim($_REQUEST['rumple']) . "'");

             sqlStatement("insert into groups set name = '" . trim($_REQUEST['groupname']) .
                    "', user = '" . trim($_REQUEST['rumple2']) . "'");
            
            $query = "INSERT INTO users_facility (tablename, table_id, facility_id) VALUES ('users', $prov_id, ".$_REQUEST['facility_id'].");";
            sqlStatement( $query );	
            
            $query = "insert into user_handler (handler_id, user_id)"
                    . " values ($prov_id, $prov_id)";
            sqlStatement( $query );
            
            if (isset($phpgacl_location) && acl_check('admin', 'acl') && trim($_REQUEST['rumple2'])) {
                // Set the access control group of user
                set_user_aro($_REQUEST['access_group'], trim($_REQUEST['rumple2']), trim($_REQUEST['fname']), trim($_REQUEST['mname']), trim($_REQUEST['lname']));
            }

            $ws = new WSProvider($prov_id);
            
            echo $prov_id;
        } else {
            $alertmsg .= xl('User', '', '', ' ') . trim($_REQUEST['rumple2']) . xl('already exists.', '', ' ');
        }
        if ($_REQUEST['access_group']) {
            $bg_count = count($_REQUEST['access_group']);
            for ($i = 0; $i < $bg_count; $i++) {
                if ($_REQUEST['access_group'][$i] == "Emergency Login") {
                    $set_active_msg = 1;
                }
            }
        }
    } else if ($_REQUEST["mode"] == "new_group") {
        $res = sqlStatement("select distinct name, user from groups");
        for ($iter = 0; $row = sqlFetchArray($res); $iter++)
            $result[$iter] = $row;
        $doit = 1;
        foreach ($result as $iter) {
            if ($doit == 1 && $iter{"name"} == trim(formData('groupname')) && $iter{"user"} == trim(formData('rumple')))
                $doit--;
        }
        if ($doit == 1) {
            sqlStatement("insert into groups set name = '" . trim(formData('groupname')) .
                    "', user = '" . trim(formData('rumple')) . "'");
        } else {
            $alertmsg .= "User " . trim(formData('rumple')) .
                    " is already a member of group " . trim(formData('groupname')) . ". ";
        }
    }
}

if (isset($_REQUEST["mode"])) {

    /*     * *****************************************************************
      // This is the code to delete a user.  Note that the link which invokes
      // this is commented out.  Somebody must have figured it was too dangerous.
      //
      if ($_REQUEST["mode"] == "delete") {
      $res = sqlStatement("select distinct username, id from users where id = '" .
      $_REQUEST["id"] . "'");
      for ($iter = 0; $row = sqlFetchArray($res); $iter++)
      $result[$iter] = $row;

      // TBD: Before deleting the user, we should check all tables that
      // reference users to make sure this user is not referenced!

      foreach($result as $iter) {
      sqlStatement("delete from groups where user = '" . $iter{"username"} . "'");
      }
      sqlStatement("delete from users where id = '" . $_REQUEST["id"] . "'");
      }
     * ***************************************************************** */

    if ($_REQUEST["mode"] == "delete_group") {
        $res = sqlStatement("select distinct user from groups where id = '" .
                $_REQUEST["id"] . "'");
        for ($iter = 0; $row = sqlFetchArray($res); $iter++)
            $result[$iter] = $row;
        foreach ($result as $iter)
            $un = $iter{"user"};
        $res = sqlStatement("select name, user from groups where user = '$un' " .
                "and id != '" . $_REQUEST["id"] . "'");

        // Remove the user only if they are also in some other group.  I.e. every
        // user must be a member of at least one group.
        if (sqlFetchArray($res) != FALSE) {
            sqlStatement("delete from groups where id = '" . $_REQUEST["id"] . "'");
        } else {
            $alertmsg .= "You must add this user to some other group before " .
                    "removing them from this group. ";
        }
    }
}

$form_inactive = empty($_REQUEST['form_inactive']) ? false : true;
?>